package com.cssw.fyzb.tps.api.pay;

import com.cssw.fyzb.tps.service.pay.WxPayService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: chenchao
 * @Date: 2020/7/14 22:10
 */

@Function(description = "微信订单查询", parameters = {
        @Parameter(name = "tradeNo", type = Type.String, description = "流水号", required = true),
})
@Component
public class WxOrderQuery implements Action {

    private static final Logger logger = LoggerFactory.getLogger(WxOrderQuery.class);

    @Autowired
    private WxPayService wxPayService;


    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String tradeNo = request.getString("tradeNo");

        Map<String, String> map = wxPayService.orderQuery(tradeNo);

        logger.info(tradeNo + ">>>WxOrderQuery:" + userId + ">>>" + map);

        //SUCCESS/FAIL 此字段是通信标识，非交易标识，交易是否成功需要查看trade_state来判断
        String returnCode = map.get("return_code");

        if (!"SUCCESS".equals(returnCode)) {
            return Response.fail("订单不存在");
        }

        String resultCode = map.get("result_code");
        if (!"SUCCESS".equals(resultCode)) {
            return Response.fail("订单错误");
        }

        //SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVOKED—已撤销（付款码支付） USERPAYING--用户支付中（付款码支付） PAYERROR--支付失败(其他原因，如银行返回失败)
        String tradeState = map.get("trade_state");
        if (!"SUCCESS".equals(tradeState)) {
            return Response.fail("未支付");
        }

        Map dataMap = new HashMap();
        dataMap.put("totalFee", map.get("total_fee"));
        dataMap.put("transactionId", map.get("transaction_id"));
        return Response.success().put("data", dataMap);
    }
}